<script lang="ts">
export default {
  name: 'DailyFaultReport',
};
</script>

<!-- 日常故障统计  -->

<script setup lang="ts">
import { computed, ref } from 'vue';
import { ArrowUpIcon, RectangleIcon } from 'tdesign-icons-vue-next';
import dayjs from 'dayjs';
import proxy from '@/config/proxy';

const dateQuery = ref('');

const headers = ref({
  Authorization: `Bearer ${import.meta.env.VITE_DIFY_API_KEY}`,
});

const props = defineProps({
  message: { type: String, default: '' }, // 移除父组件默认值
  files: Array,
  inputs: Object,
  isLoading: Boolean,
});

const emit = defineEmits([
  'update:message',
  'update:files',
  'update:inputs',
  'send-message',
  'recover-event',
  'handle-upload-confirm',
  'stop-message',
]);

// 使用计算属性实现双向绑定
const localFiles = computed({
  get: () => props.files,
  set: (value) => emit('update:files', value),
});

// 使用计算属性实现双向绑定
const inputMessage = computed({
  get: () => props.message,
  set: (value) => emit('update:message', value),
});

// 使用计算属性实现双向绑定

const onCancelUpload = () => {
  console.log('cancel upload');
};
const onRemove = () => {
  console.log('remove file');
};

const seedDefaultMessage = () => {
  // 解构获取时间范围
  // eslint-disable-next-line camelcase
  const [start_time, end_time] = dateQuery.value;
  console.log('[start_time, end_time]', [start_time, end_time]);
  // 日期格式化函数，使用 dayjs
  const formatDate = (dateString) => {
    const date = dayjs(dateString);
    return date.isValid() ? date.format('YYYY年MM月DD日') : '无效日期';
  };

  // 格式化时间范围
  const formattedDates = {
    start: formatDate(start_time),
    end: formatDate(end_time),
  };

  // 拼接提示语（带异常处理）
  const generateMessage = () => {
    try {
      return `请生成${formattedDates.start}至${formattedDates.end}的日常故障统计报表`;
    } catch (e) {
      console.error('消息生成失败:', e);
      return '请生成日常故障统计报表'; // 降级处理
    }
  };

  // 更新父组件状态
  emit('update:inputs', { start_time, end_time });
  emit('update:message', generateMessage());
  emit('send-message');

  // 调试日志（开发环境）
  if (import.meta.env.DEV) {
    console.log('日期参数:', { start_time, end_time });
    console.log('格式化结果:', formattedDates);
  }
};

const handleUploadSuccess = ({ fileList }) => {
  emit('update:files', fileList); // 确保更新父组件值
};
// 计算上传地址
const uploadAction = computed(() => `${proxy.development.host}/files/upload`);

// 日期选择
const onPick = (value, context) => {
  console.log('onPick:', value, context);
};
const onChange = (value, context) => {
  console.log('onChange:', value, context);
  console.log(
    'timestamp:',
    context.dayjsValue.map((d) => d.valueOf()),
  );
  console.log(
    'YYYYMMDD:',
    context.dayjsValue.map((d) => d.format('YYYYMMDD')),
  );
};
</script>

<template>
  <div class="input-area-container">
    <t-col class="input-with-button">
      <div class="input-box">
        <t-tooltip content="点击退出场景" class="input-type-title">
          <div @click="emit('recover-event')"><t-icon name="chevron-left" />日常故障统计</div>
        </t-tooltip>
        <t-date-range-picker
          v-model="dateQuery"
          size="small"
          class="input-date"
          style="min-width: calc(100% - 180px)"
          allow-input
          clearable
          @pick="onPick"
          @change="onChange"
        />
      </div>
      <div class="action-buttons">
        <t-upload
          v-model="localFiles"
          class="file-box"
          :headers="headers"
          :auto-upload="true"
          theme="file"
          :data="{ user: 'user123' }"
          :abridge-name="[10, 8]"
          draggable=""
          :action="uploadAction"
          @cancel-upload="onCancelUpload"
          @remove="onRemove"
          @success="handleUploadSuccess"
        />
        <t-button
          v-if="!isLoading"
          :disabled="!localFiles.length > 0"
          class="send-btn"
          shape="circle"
          theme="primary"
          @click="seedDefaultMessage"
        >
          <template #icon>
            <arrow-up-icon />
          </template>
        </t-button>
        <t-button v-else class="stop-btn" shape="circle" theme="primary" @click="$emit('stop-message')">
          <template #icon>
            <rectangle-icon style="background-color: white; font-size: 12px" />
          </template>
        </t-button>
      </div>
    </t-col>
  </div>
</template>

<style scoped lang="less">
@import url('../index.less');
:deep(.t-upload__dragger) {
  width: 100%;
  margin-top: 10px;
}
:deep(.t-range-input) {
  margin-left: 15px;
}
</style>
